import socket
import json
import time
import random
import math
from datetime import datetime

# TCP 服务器配置
HOST = '47.108.225.245'
PORT = 9998

# 模拟的起始位置（北京天安门）
start_lat = 39.90858
start_lng = 116.39142
speed = 0.0001

def generate_location(current_lat, current_lng, current_direction):
    """生成位置数据"""
    # 随机改变方向
    if random.random() < 0.1:
        current_direction = random.uniform(0, 2 * math.pi)
    
    # 计算新位置
    new_lat = current_lat + speed * math.sin(current_direction)
    new_lng = current_lng + speed * math.cos(current_direction)
    
    # 生成数据
    data = {
        'latitude': new_lat,
        'longitude': new_lng,
        'timestamp': datetime.now().isoformat(),
        'speed': random.uniform(0, 60),
        'heading': math.degrees(current_direction),
        'accuracy': random.uniform(1, 10)
    }
    
    return data, new_lat, new_lng, current_direction

def main():
    # 创建 TCP 客户端
    client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    
    try:
        # 连接服务器
        client.connect((HOST, PORT))
        print(f'已连接到服务器 {HOST}:{PORT}')
        
        current_lat = start_lng
        current_lng = start_lat
        current_direction = random.uniform(0, 2 * math.pi)  # 初始化方向
        
        while True:
            # 生成位置数据
            data, current_lat, current_lng, current_direction = generate_location(
                current_lat, current_lng, current_direction
            )
            
            # 只发送“纬度,经度”字符串
            message = f"{data['latitude']:.6f},{data['longitude']:.6f}\n"
            
            # 发送数据
            client.send(message.encode('utf-8'))
            print(f'发送: {message.strip()}')
            
            # 等待一秒
            time.sleep(1)
            
    except KeyboardInterrupt:
        print('\n停止发送')
    except Exception as e:
        print(f'错误: {e}')
    finally:
        client.close()
        print('连接已关闭')

if __name__ == '__main__':
    main() 